import axios from 'axios'
import {
  Message,
  Loading
} from 'element-ui'
import {
  getUserId
} from '@/utils/auth'
import md5 from 'js-md5'

// 全局添加loading  暂时关闭
let loading = null

// 开始 加载loading
const startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.3)'
  })
}
// 结束 取消loading加载
const endLoading = () => {
  loading.close()
}

// showFullScreenLoading() 与 tryHideFullScreenLoading() 目的是合并同一页面多个请求触发loading

let needLoadingRequestCount = 0 // 声明一个变量

const showFullScreenLoading = () => {
  if (needLoadingRequestCount === 0) { // 当等于0时证明第一次请求 这时开启loading
    startLoading()
  }
  // 全局变量值++
  needLoadingRequestCount++
}

const tryHideFullScreenLoading = () => {
  if (needLoadingRequestCount <= 0) return // 小于等于0 证明没有开启loading 此时return
  needLoadingRequestCount-- // 正常响应后 全局变量 --
  if (needLoadingRequestCount === 0) { // 等于0 时证明全部加载完毕 此时结束loading 加载
    endLoading()
  }
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 100000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 开启loading加载
    showFullScreenLoading()
    // do something before request is sent
    const KEY = '0b8d21e9c1572cdf61e9862f786b568d'
    const SECRET = '8ffdd469dc7bcb75'
    const time = Date.now()
    config.headers['key'] = KEY
    config.headers['timestamp'] = time
    config.headers['token'] = config.headers.token ? config.headers.token : md5(KEY + time + SECRET)
    config.headers['userId'] = getUserId() || '123456'
    return config
  },
  error => {
    // 关闭loading加载
    tryHideFullScreenLoading()
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // 关闭loading加载
    tryHideFullScreenLoading()
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    // 关闭loading加载
    tryHideFullScreenLoading()
    Message({
      message: error,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }

)

export default service
